<?php

use \Zizaco\Confide\ConfideUser;
use Zizaco\Confide\ConfideUserInterface;
use \Zizaco\Entrust\HasRole;

class User extends Eloquent implements ConfideUserInterface {

	use HasRole, ConfideUser;

	/**
	 * The database table used by the model.
	 *
	 * @var string
	 */
	protected $table = 'users';

    const STAFF = 'Staff';
    const MEMBER = "Member";

	/**
	 * The attributes excluded from the model's JSON form.
	 *
	 * @var array
	 */
	protected $hidden = array('password', 'remember_token');

    public static $rules = array(
        'username' => 'required|alpha_dash|unique:users',
        'password' => 'required|min:4|confirmed',
        'password_confirmation' => 'min:4',
        'email' => 'required|email',
    );

    public function attach()
    {
        return $this->morphTo();
    }

    /**
     * Save roles inputted from multiselect
     * @param $inputRoles
     */
    public function saveRoles($inputRoles)
    {
        if(! empty($inputRoles)) {
            $this->roles()->sync($inputRoles);
        } else {
            $this->roles()->detach();
        }
    }

    public function name(){
        if($this->isStaff()){
            return $this->attach->name;
        }
        if($this->isMember()){
            return $this->attach->nick_name;
        }
        return $this->username;
    }

    public function isStaff(){
        return $this->attach_type == self::STAFF;
    }

    public function isMember(){
        return $this->attach_type == self::MEMBER;
    }

    /**
     * Returns user's current role ids only.
     * @return array|bool
     */
    public function currentRoleIds()
    {
        $roles = $this->roles;
        $roleIds = false;
        if( !empty( $roles ) ) {
            $roleIds = array();
            foreach( $roles as &$role )
            {
                $roleIds[] = $role->id;
            }
        }
        return $roleIds;
    }

    public function getRoleNamesArray(){
        $arrRoles =array();
        foreach($this->roles as $role){
            $arrRoles[] = $role->display_name;
        }
        return $arrRoles;
    }

    /**
     * 删除用户前判断是否含有相关信息，如有，不允许删除
     * @param bool $forced
     * @return bool
     */
    public function beforeDelete( $forced = false )
    {
        try {
            //判断是否含有相关信息


        } catch(Execption $e) {
            $this->errors()->add('error', $e->getMessage());
            return false;
        }
        return true;
    }
}
